package com.jf.docsify.modules.system.user;

import java.util.List;

import org.apache.commons.collections4.CollectionUtils;

import com.jf.docsify.common.exception.DocsifyException;
import com.jf.docsify.common.utils.AssertUtil;
import com.jf.docsify.common.utils.DbTxUtil;
import com.jf.docsify.common.utils.SecurityUtil;
import com.jf.docsify.modules.model.SysAuthRegister;
import com.jf.docsify.modules.model.SysUser;
import com.jf.docsify.modules.orgz.OrganizationService;
import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.SqlPara;

/**
 * Description: 用户服务层
 *
 * @author chenwr
 * @version 1.0
 *
 * <pre>
 * 修改记录:
 * 修改后版本           修改人       修改日期         修改内容
 * 2022/7/26.1       chenwr    2022/7/26           Create
 * </pre>
 * @date 2022/7/26
 */
public class UserService {

    private SysUser dao = new SysUser().dao();

    @Inject
    OrganizationService organizationService;

    @Inject
    AuthRegisterService authRegisterService;

    /**
     * 新增用户
     * @param sysUser 密码字段： 需传入经过md5 后的密码文本
     */
    public void addOrUpdate(SysUser sysUser) {
        SysUser user = new SysUser();
        String userName = sysUser.getUserName();
        String password = sysUser.getPassword();
        AssertUtil.hasText(userName, "用户名不能为空");
        AssertUtil.hasText(password, "密码不能为空");
        List<SysUser> sysUsers = findByUserName(userName);
        user.setUserName(userName);
        password = SecurityUtil.md5(password);
        user.setPassword(password);
        if (CollectionUtils.isEmpty(sysUsers)) {
            DbTxUtil.tx(() -> {
                user.save();
                // 添加默认组织
                organizationService.save("默认", userName, user.getId(), "默认组织");
            });
            return;
        }
        String pwdOld = sysUser.getPwdOld();
        AssertUtil.hasText(pwdOld, "原密码不能为空");
        pwdOld = SecurityUtil.md5(pwdOld);
        String passwordOld = sysUsers.get(0).getPassword();
        if (pwdOld.equals(passwordOld)) {
            DocsifyException.throwE("原密码不正确，请重试");
        }
        user.setId(sysUsers.get(0).getId());
        user.update();
    }

    public void delete(SysUser sysUser) {
        String userName = sysUser.getUserName();
        AssertUtil.hasText(userName, "用户名不能为空");
        SqlPara sqlPara = new SqlPara();
        sqlPara.setSql("select * from sys_user where user_name = ?");
        sqlPara.addPara(userName);
        List<SysUser> sysUsers = dao.find(sqlPara);
        if (CollectionUtils.isEmpty(sysUsers)) {
            DocsifyException.throwE("未找到对应用户");
        }
        SysUser user = sysUsers.get(0);
        user.delete();
    }

    public SysUser find(SysUser sysUser) {
        AssertUtil.notNull(sysUser, "用户名或密码不能为空");
        String userName = sysUser.getUserName();
        AssertUtil.hasText(userName, "用户名或密码不能为空");
        String password = sysUser.getPassword();
        AssertUtil.hasText(password, "用户名或密码不能为空");
        SqlPara sqlPara = new SqlPara();
        sqlPara.setSql("select * from sys_user where user_name = ? and password = ?");
        sqlPara.addPara(userName);
        sqlPara.addPara(SecurityUtil.md5(password));
        List<SysUser> sysUsers = dao.find(sqlPara);
        AssertUtil.notEmpty(sysUsers, "用户名或密码错误");
        SysUser user = sysUsers.get(0);
        AssertUtil.notNull(user, "用户名或密码错误");
        return user;
    }

    public boolean register(SysUser sysUser) {
        String userName = sysUser.getUserName();
        String password = sysUser.getPassword();
        AssertUtil.hasText(userName, "用户名不能为空");
        AssertUtil.hasText(password, "密码不能为空");
        List<SysAuthRegister> sysAuthRegisters = authRegisterService.authRegister(userName);
        boolean hasRegisterAuth = authRegisterService.validateHasRegisterAuth(sysAuthRegisters);
        if (!hasRegisterAuth) {
            DocsifyException.throwE("无注册权限");
        }
        List<SysUser> sysUsers = sysUser.find("select * from sys_user where user_name = ?", userName);
        if (CollectionUtils.isNotEmpty(sysUsers)) {
            DocsifyException.throwE("用户名已存在，请更改后重试");
        }
        password = SecurityUtil.md5(password);
        sysUser.setPassword(password);
        return DbTxUtil.tx(() -> {
            sysUser.save();
            // 添加默认组织
            organizationService.save("默认", userName, sysUser.getId(), "默认组织");
            authRegisterService.delete(sysAuthRegisters);
        });
    }

    public List<SysUser> findByUserName(String userName) {
        AssertUtil.hasText(userName, "用户名不能为空");
        return dao.find("select * from sys_user where user_name = ?", userName);
    }

    public boolean update(SysUser sysUser) {
        String pwdOld = sysUser.getPwdOld();
        String userName = sysUser.getUserName();
        String password = sysUser.getPassword();
        AssertUtil.hasText(pwdOld, "原密码不能为空");
        AssertUtil.hasText(userName, "用户名不能为空");
        AssertUtil.hasText(password, "新密码不能为空");
        List<SysUser> sysUsers = findByUserName(userName);
        AssertUtil.notEmpty(sysUsers, "未找到对应的用户信息");
        SysUser oldUser = sysUsers.get(0);
        pwdOld = SecurityUtil.md5(pwdOld);
        String passwordOld = oldUser.getPassword();
        if (!pwdOld.equals(passwordOld)) {
            DocsifyException.throwE("原密码不正确，请重试");
        }
        SysUser user = new SysUser();
        password = SecurityUtil.md5(password);
        user.setPassword(password);
        user.setUserName(userName);
        user.setId(oldUser.getId());
        return user.update();
    }
}